package org.jeecgframework.web.demo.controller.test;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.UUIDGenerator;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.demo.entity.test.FileMeta;
import org.jeecgframework.web.service.ZyFileLogServiceI;
import org.jeecgframework.web.service.ZyInspectionReportServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 类 名 称： FileUploadController 类 描 述： jQuery File Upload 例子 创 建 人： yiming.zhang
 * 联系方式： 1374250553@qq.com 创建时间： 2014-2-19 下午11:25:22
 * <p>
 * 修 改 人： Administrator 操作时间： 2014-2-19 下午11:25:22 操作原因：
 */
@Scope("prototype")
@Controller
@RequestMapping("/fileUploadController")
public class FileUploadController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(FileUploadController.class); // NOPMD by dzqThinkpad on
    // 16-4-1 下午3:04

    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyInspectionReportServiceI zyInspectionReportService;
    @Autowired
    private ZyFileLogServiceI zyFileLogService;
    private String message;

    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    FileMeta fileMeta = null;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * 方法描述: (这里用一句话描述这个方法的作用) 作 者： yiming.zhang 日 期： 2014-2-20-下午10:27:45
     *
     * @param request
     * @return 返回类型： ModelAndView
     */
    @RequestMapping(params = "fileUploadSample")
    public ModelAndView webOfficeSample(HttpServletRequest request) {
        return new ModelAndView("jeecg/demo/test/fileUploadSample");
    }

    @RequestMapping(params = "upload", method = RequestMethod.POST)
    @ResponseBody
    public LinkedList<FileMeta> upload(MultipartHttpServletRequest request,
                                       HttpServletResponse response) {
        // 1. build an iterator
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf = null;

        // 2. get each file
        while (itr.hasNext()) {

            // 2.1 get next MultipartFile
            mpf = request.getFile(itr.next());

            // 2.2 if files > 10 remove the first from the list
            if (files.size() >= 10)
                files.pop();

            // 2.3 create new fileMeta
            fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            fileMeta.setFileType(mpf.getContentType());

            try {
                fileMeta.setBytes(mpf.getBytes());

                String path = "upload/";
                String realPath = request.getSession().getServletContext()
                        .getRealPath("/")
                        + "/" + path;// 文件的硬盘真实路径
                String savePath = realPath + mpf.getOriginalFilename();// 文件保存全路径

                // copy file to local disk (make sure the path
                // "e.g. D:/temp/files" exists)
                FileCopyUtils.copy(mpf.getBytes(), new File(savePath));

            } catch (IOException e) {
                e.printStackTrace();
            }
            // 2.4 add to files
            files.add(fileMeta);

        }

        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
        return files;
    }


    @RequestMapping(params = "view", method = {RequestMethod.GET,
            RequestMethod.POST})
    public void get(HttpServletResponse response, String index) {
        FileMeta getFile = files.get(Integer.parseInt(index));
        try {
            response.setContentType(getFile.getFileType());
            response.setHeader("Content-disposition", "attachment; filename=\""
                    + getFile.getFileName() + "\"");
            FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param req
     * @param multi  是否是多文件
     * @param extend 允许上传的文件扩展名 eg: *.xls
     * @return
     * @author xiul
     * 2016-4-12 下午4:09:08
     * Description 跳转至文件上传页面
     */
    @RequestMapping(params = "goUploadAttachment")
    public ModelAndView uploadAttachment(
            HttpServletRequest req,
            @RequestParam(value = "multi", required = false, defaultValue = "true") boolean multi,
            @RequestParam(value = "extend", required = false, defaultValue = "*") String extend,
            @RequestParam(value = "noAttachTipId", required = false, defaultValue = "") String noAttachTipId,
            @RequestParam(value = "attachSpanId", required = false, defaultValue = "") String attachSpanId
    ) {
        req.setAttribute("multi", multi);
        req.setAttribute("extend", extend);
        req.setAttribute("noAttachTipId", noAttachTipId);
        req.setAttribute("attachSpanId", attachSpanId);

        return new ModelAndView("com/zybk/zy_upload/uploadAttachment");
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2016-4-14 下午3:38:05
     * Description 文件上传请求
     */
    @ResponseBody
    @RequestMapping(params = "uploadFile")
    public AjaxJson uploadFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String businessKey = oConvertUtils.getString(request.getParameter("businessKey"));// 业务ID
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessKey(businessKey);
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2016-4-14 下午3:38:05
     * Description 服务单文件上传请求
     */
    @ResponseBody
    @RequestMapping(params = "uploadFileService")
    public AjaxJson uploadFileService(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String businessKey = oConvertUtils.getString(request.getParameter("businessKey"));// 业务ID
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessKey(businessKey);
            zyfileLog.setBusinessType("D");
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 返件明细上传信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "uploadFileReturn")
    public AjaxJson uploadFileReturn(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String businessKey=request.getParameter("businessKey");
        String childKey=request.getParameter("childKey");
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessType("E");
            zyfileLog.setBusinessKey(businessKey);
            zyfileLog.setBusinessChildType(childKey);
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 返件入库明细上传信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "uploadFileBack")
    public AjaxJson uploadFileBack(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String businessKey=request.getParameter("businessKey");
        String childKey=request.getParameter("childKey");
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessType("H");
            zyfileLog.setBusinessKey(businessKey);
            zyfileLog.setBusinessChildType(childKey);
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2016-4-14 下午3:38:05
     * Description 文件上传请求
     */
    @ResponseBody
    @RequestMapping(params = "uploadFileView")
    public AjaxJson uploadFileView(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            ZyFileLogEntity zyfileLog = null;
            String businessKey = oConvertUtils.getString(request.getParameter("businessKey"));// 业务ID
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            List<ZyFileLogEntity> zyFileLogEntityList = systemService.findByProperty(ZyFileLogEntity.class, "businessKey", businessKey);
            if (zyFileLogEntityList.size() > 0) {
                zyfileLog = zyFileLogEntityList.get(0);
                zyfileLog.setBusinessKey(businessKey);
                zyfileLog.setFilePath(fileBean.getSavePath());
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                systemService.save(zyfileLog);
            } else {
                zyfileLog = new ZyFileLogEntity();
                zyfileLog.setBusinessKey(businessKey);
                zyfileLog.setFilePath(fileBean.getSavePath());
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                systemService.save(zyfileLog);
            }

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @param request
     * @param response
     * @param
     * @author xiul
     * 2016-4-14 下午3:29:55
     * Description 文件下载请求
     */
    @ResponseBody
    @RequestMapping(params = "downLoadFile")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "fileLogId", defaultValue = "") String fileLogId) {
        ZyFileLogEntity zyFileLogEntity = systemService.get(ZyFileLogEntity.class, fileLogId);
        if (zyFileLogEntity != null) {
            try {
                UploadFileUtil.downFile(request, response, new FileBean(zyFileLogEntity.getFilePath(), zyFileLogEntity.getOldFileName()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @author xiul
     * 2016-8-23 下午4:34:13
     * Description APP - 上传巡检报告附件
     */
    @ResponseBody
    @RequestMapping(params = "uploadIrFile")
    public AjaxJson uploadIrFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String irId = request.getParameter("irId");// 巡检报告ID
            String attachType = request.getParameter("attachType");
            String esSn = request.getParameter("esSn");//设备序列号
            String ipId = request.getParameter("ipId");//巡检计划ID
            String esType = request.getParameter("esType");//机型
            String imgCase = request.getParameter("imgCase");//项目类型

            String compressFileStr = request.getParameter("compressFile");
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);

            //MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            //MultipartFile multipartFile = req.getFile("Filedata");
            //String fileRealName = multipartFile.getOriginalFilename();
            //String suffix = fileRealName.substring(fileRealName.lastIndexOf("."));
            String suffix = ".jpg";

			/*CommonsMultipartFile cf= (CommonsMultipartFile)multipartFile;
            DiskFileItem fi = (DiskFileItem)cf.getFileItem();
	        File mFile = fi.getStoreLocation();
			Metadata metadata = ImageMetadataReader.readMetadata(mFile);
			ExifSubIFDDirectory exifDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);//指定获取
			if(null != exifDir){
				Date originalDate = exifDir.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
				if(null != originalDate){
					System.out.println(originalDate);
				}else{
					System.err.println("文件不正确");
				}
			}else{
				System.err.println("文件不正确");
			}*/

//			Iterable<Directory> exifs = metadata.getDirectories();//获得所有
//			Iterator<Directory> itr = exifs.iterator();
//			while(itr.hasNext()){
//				Directory dir = itr.next();
//				Collection<Tag> tags = dir.getTags();
//				for (Tag tag : tags) {
//					if(tag.getTagName().equals("Date/Time Original")){
//						System.err.println(tag.getDescription());
//					}
//					System.out.print(">>" + tag + "<<");
//					System.out.print(">>" + tag.getDirectoryName() + "<<");
//					System.out.print(">>" + tag.getDescription() + "<<");
//					System.out.print(">>" + tag.getTagName() + "<<");
//					System.out.println();
//				}
//			}
            ZyInspectionPlanEntity zyIp = systemService.get(ZyInspectionPlanEntity.class, ipId);
            String planId = "";
            if (null != zyIp) {
                planId = zyIp.getPlanId();
            }
            String fileReName = "";//APP 端文件上传的文件名不符合PC端规则。需要后台处理
            if (attachType.equals(StaticValue.DIC_REPORT_ATTACH_TYPE_INSPECTION_IMAGE)) {//巡检图片
                //巡检图片命名规则为：设备序列号_项目_YYYY-MM-DD
                fileReName = esSn + "_" + imgCase + "_" + year + "-" + month + "-" + day + suffix;
            } else if (attachType.equals(StaticValue.DIC_REPORT_ATTACH_TYPE_COMPLETION_IMAGE)) {//巡检完工单
                //巡检完工单照片命名规则为：巡检完工单_巡检计划ID_机型_设备序列号_YYYY-MM-DD
                fileReName = "巡检完工单_" + planId + "_" + esType + "_" + esSn + "_" + year + "-" + month + "-" + day + suffix;
            }
            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);

            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                j.setMsg("图片为空");
                j.setSuccess(false);
            }
            FileBean fileBean = new FileBean();
            fileBean.setFileName(newFileName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(fileReName);
            fileBean.setSavePath(file.getAbsolutePath());

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessKey(irId);
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            zyInspectionReportService.saveAttachment(irId, new String[]{zyfileLog.getId()}, attachType);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @author xiul
     * 2017-4-7 下午6:08:28
     * Description Ckeditor编辑器上传图片
     */
    @ResponseBody
    @RequestMapping(params = "ckeditorUploadImages")
    public void ckeditorUploadImages(HttpServletRequest request, HttpServletResponse response) {
        try {
            FileBean fileBean = UploadFileUtil.uploadCkeditorImages(request);

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            systemService.save(zyfileLog);

            response.setContentType("text/html;charset=UTF-8");
            String callback = request.getParameter("CKEditorFuncNum");
            PrintWriter out = response.getWriter();
            String imagePath = "fileUploadController.do?downLoadFile&fileLogId=" + zyfileLog.getId();
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imagePath + "',''" + ")");
            out.println("</script>");
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String businessKey = request.getParameter("businessKey");
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findByProperty(ZyFileLogEntity.class, "businessKey", businessKey);
        if (zyFileLogEntityList.size() > 0) {
            for (ZyFileLogEntity zyFileLogEntity : zyFileLogEntityList) {
                try {
                    zyFileLogService.deleteFileLogAndFile(zyFileLogEntity.getId());
                } catch (Exception e) {
                    j.setMsg("删除附件失败");
                    j.setSuccess(false);
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
    @ResponseBody
    @RequestMapping(params = "delFiles")
    public AjaxJson delFiles(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String businessKey = request.getParameter("businessKey");
        ZyFileLogEntity zyFileLogEntityList = systemService.getEntity(ZyFileLogEntity.class,  businessKey);
        if (StringUtil.isNotEmpty(zyFileLogEntityList)) {

                try {
                    zyFileLogService.delete(zyFileLogEntityList);
                    j.setSuccess(true);
                } catch (Exception e) {
                    j.setMsg("删除附件失败");
                    j.setSuccess(false);
                    e.printStackTrace();
                }

        }
        return j;
    }
    /**
     * 删除返件备件照片
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFileReturn")
    public AjaxJson delFileReturn(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("id");
        ZyFileLogEntity zyFileLogEntity = systemService.get(ZyFileLogEntity.class, id);
                try {
                    zyFileLogService.delete(zyFileLogEntity);

                } catch (Exception e) {
                    j.setMsg("删除附件失败");
                    j.setSuccess(false);
                    e.printStackTrace();
                }

        return j;
    }


    /**
     * @author xiul
     * 2016-8-23 下午4:34:13
     * Description APP - 上传服务单到货异常附件
     */
    @ResponseBody
    @RequestMapping(params = "uploadServiceFile")
    public AjaxJson uploadServiceFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String ipId = request.getParameter("ipId");//服务单ID
            String attachType = request.getParameter("attachType");
            String imgCase = request.getParameter("imgCase");//项目类型

            String compressFileStr = request.getParameter("compressFile");
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);
            String suffix = ".jpg";

            String fileReName = imgCase + "_" + year + "-" + month + "-" + day + suffix;

            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);

            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                j.setMsg("图片为空");
                j.setSuccess(false);
            }
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, ipId);
            FileBean fileBean = new FileBean();
            fileBean.setFileName(newFileName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(fileReName);
            fileBean.setSavePath(file.getAbsolutePath());

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            zyfileLog.setBusinessType("G"); //到货异常照片
            systemService.save(zyfileLog);

            CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
            cbsServiceLog.setCbsServiceId(cbsServiceEntity);
            cbsServiceLog.setLogType(1);
            cbsServiceLog.setDescription("收货异常文件");
            cbsServiceLog.setZyFileLogId(zyfileLog);
            systemService.save(cbsServiceLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }


    /**
     * @author xiul
     * 2016-8-23 下午4:34:13
     * Description APP - 上传服务单故障照片
     */
    @ResponseBody
    @RequestMapping(params = "uploadServiceErrorFile")
    public AjaxJson uploadServiceErrorFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String attachType = request.getParameter("attachType");//故障照片类型
            String imgCase = request.getParameter("imgCase");//项目类型

            String compressFileStr = request.getParameter("compressFile");
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);
            String suffix = ".jpg";

            String fileReName = imgCase + "_" + year + "-" + month + "-" + day + suffix;

            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);

            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                j.setMsg("图片为空");
                j.setSuccess(false);
            }

            FileBean fileBean = new FileBean();
            fileBean.setFileName(newFileName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(fileReName);
            fileBean.setSavePath(file.getAbsolutePath());

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            zyfileLog.setBusinessType("D"); //故障异常照片
            systemService.save(zyfileLog);
            CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
            cbsServiceLog.setLogType(1);
            cbsServiceLog.setDescription("故障异常照片");
            cbsServiceLog.setZyFileLogId(zyfileLog);
            systemService.save(cbsServiceLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }


    /**
     * @author xiul
     * 2016-8-23 下午4:34:13
     * Description APP - 上传备件附件
     */
    @ResponseBody
    @RequestMapping(params = "uploadSpareFile")
    public AjaxJson uploadSpareFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String ipId = request.getParameter("ipId");//服务单ID
            String attachType = request.getParameter("attachType");
            String imgCase = request.getParameter("imgCase");//项目类型
            String compressFileStr = request.getParameter("compressFile");
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);
            String suffix = ".jpg";

            String fileReName = imgCase + "_" + year + "-" + month + "-" + day + suffix;

            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);

            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                j.setMsg("图片为空");
                j.setSuccess(false);
            }
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, ipId);
            FileBean fileBean = new FileBean();
            fileBean.setFileName(newFileName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(fileReName);
            fileBean.setSavePath(file.getAbsolutePath());

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileRealName());
            zyfileLog.setNewFileName(fileBean.getFileName());
            zyfileLog.setBusinessType("F");
            systemService.save(zyfileLog);

            CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
            cbsServiceLog.setCbsServiceId(cbsServiceEntity);
            cbsServiceLog.setLogType(1);
            cbsServiceLog.setDescription("备件申请附件");
            cbsServiceLog.setZyFileLogId(zyfileLog);
            systemService.save(cbsServiceLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }


    /**
     * 返件明细APP上传信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "uploadFileAppReturn")
    public AjaxJson uploadFileAppReturn(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> attributes = new HashMap<String, Object>();
            String businessKey=request.getParameter("businessKey");
            String compressFileStr = request.getParameter("compressFile");
            Calendar cld = Calendar.getInstance();
            int year = cld.get(Calendar.YEAR);
            int month = cld.get(Calendar.MONTH) + 1;
            int day = cld.get(Calendar.DAY_OF_MONTH);
            String suffix = ".jpg";
            String fileReName = "返件详情附件_" + year + "-" + month + "-" + day + suffix;
            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);

            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                j.setMsg("图片为空");
                j.setSuccess(false);
            }

            FileBean fileBean = new FileBean();
            fileBean.setFileName(fileReName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(newFileName);
            fileBean.setSavePath(file.getAbsolutePath());

            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setBusinessType("E");
            zyfileLog.setBusinessChildType(businessKey);
            zyfileLog.setFilePath(fileBean.getSavePath());
            zyfileLog.setOldFileName(fileBean.getFileName());
            zyfileLog.setNewFileName(fileBean.getFileRealName());
            systemService.save(zyfileLog);

            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, businessKey);
            CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
            cbsServiceLog.setCbsServiceId(cbsServiceEntity);
            cbsServiceLog.setLogType(1);
            cbsServiceLog.setDescription("返件申请附件");
            cbsServiceLog.setZyFileLogId(zyfileLog);
            systemService.save(cbsServiceLog);

            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            j.setAttributes(attributes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }
}
